# -*- coding: utf-8 -*-

# Импортируем нужные нам библиотеки
import urllib, urllib2, re, sys, os
import xbmc, xbmcplugin, xbmcaddon, xbmcgui

_ADDON_NAME =   'plugin.video.jampo.tv'
_addon      =   xbmcaddon.Addon(id=_ADDON_NAME)
_addon_id   =   int(sys.argv[1])
_addon_url  =   sys.argv[0]
_addon_path =   _addon.getAddonInfo('path').decode(sys.getfilesystemencoding())

def _string(string_id):
    return _addon.getLocalizedString(string_id).encode('utf-8')

def notify(addonId, message, timeShown=5000):
    """Displays a notification to the user
    
    Parameters:
    addonId: the current addon id
    message: the message to be shown
    timeShown: the length of time for which the notification will be shown, in milliseconds, 5 seconds by default
    """
    xbmc.executebuiltin('Notification(%s, %s, %d, %s)' % (_addon.getAddonInfo('name'), message, timeShown, _addon.getAddonInfo('icon')))

def showError(addonId, errorMessage):
    """
    Shows an error to the user and logs it
    
    Parameters:
    addonId: the current addon id
    message: the message to be shown
    """
    notify(addonId, errorMessage)
    xbmc.log(errorMessage, xbmc.LOGERROR)

def get_params():
    param=[]
    paramstring=sys.argv[2]
    if len(paramstring)>=2:
        params=sys.argv[2]
        cleanedparams=params.replace('?','')
        if (params[len(params)-1]=='/'):
            params=params[0:len(params)-2]
        pairsofparams=cleanedparams.split('&')
        param={}
        for i in range(len(pairsofparams)):
            splitparams={}
            splitparams=pairsofparams[i].split('=')
            if (len(splitparams))==2:
                param[splitparams[0]]=splitparams[1]
                            
    return param

# Функция для получения исходного кода web-страниц
def getHTML(url):
    headers = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3', 'Content-Type':'application/x-www-form-urlencoded'}
    conn = urllib2.urlopen(urllib2.Request(url, urllib.urlencode({}), headers))
    html = conn.read()
    conn.close()
    
    return html 

def video_Categories():
    url = 'http://tv.jampo.tv'
    html = getHTML(url)
    category_links = re.compile('<a href="(.+?)" title="(.+?)" >.+?</a><br />').findall(html)
    for link, title in category_links:
        addDir(title, link, 1, 'video')
        #print title, link
                
    #endListing()

def video_Channels(url):
    html = getHTML(url)
#    <a href="http://tv.jampo.tv/play/channel/1plus1/"><img src="/img/tv/1plus1.jpg" title="1+1 (1 плюс 1)" alt="1+1 (1 плюс 1)" width="80" height="80" /></a>

    channels_links = re.compile('<a href="(.+?)"><img src="(.+?)" title="(.+?)" alt=".*?" width="80" height="80" /></a>').findall(html)    
    for link, img, title in channels_links:
        html2 = getHTML(link)
        # <param name="movie" value="/files
        link2 = re.compile('<param name="movie" value="(.+?)" /><param name="flashvars" value="(.+?)" /></object>').findall(html2)
        #link2 = re.compile('<video width="600" height="480" src="(.+?)" controls />').findall(html2)
        for l1, l2 in link2:
#        if len(link2) <> 0:
            #print link2[0]
            #print link2[1]
            addLink(title,'http://tv.jampo.tv' + l1, 'http://tv.jampo.tv' + img, 'video')
        # + '&' + l2
    #endListing()

def audio_Categories():
    url = 'http://radio.jampo.tv'
    html = getHTML(url)
    category_links = re.compile('<a href="(.+?)" title="(.+?)" >.+?</a><br />').findall(html)
#    <a href="http://radio.jampo.tv/sort/category/international/" title="Міжнародні" >Міжнародні</a><br />

    for link, title in category_links:
        addDir(title, link, 1, 'audio')
        
    #endListing()

def audio_Channels(url):
#    <a href="http://radio.jampo.tv/listen/station/dj-fm/"><img src="/img/radio/dj-fm.jpg" title=" DJ FM" alt=" DJ FM" width="150" height="80" /></a>
    html = getHTML(url)
    channels_links = re.compile('<a href="(.+?)"><img src="(.+?)" title="(.+?)" alt=".*?" width="150" height="80" /></a>').findall(html)
    
    for link, img, title in channels_links:
        html2 = getHTML(link)
#        file=http://radiostreams.jampo.tv/001?type=.flv&amp;metatitle=0" />
        link2 = re.compile('file=(.+?)" />').findall(html2)
        if len(link2) <> 0:
            addLink(title,link2[0],'http://radio.jampo.tv' + img, 'audio')
        
  
def addLink(title, url, thumbnail, content_type):
    item = xbmcgui.ListItem(label=title, iconImage=thumbnail, thumbnailImage=thumbnail)
    item.setInfo( type=content_type, infoLabels={'Title': title} )

    return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=item)


def addDir(title, url, mode, content_type):
    sys_url = sys.argv[0] + '?title=' + urllib.quote_plus(title) + '&url=' + urllib.quote_plus(url) + '&mode=' + urllib.quote_plus(str(mode)) + '&content_type=' + content_type
    print sys_url
    item = xbmcgui.ListItem(title, iconImage='DefaultFolder.png', thumbnailImage='')
    item.setInfo( type=content_type, infoLabels={'Title': title} )

    return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=sys_url, listitem=item, isFolder=True)

def endListing():
    """
    Signals the end of the menu listing
    """
    xbmcplugin.endOfDirectory(int(sys.argv[1]))

def audio(mode, url, title):
    if mode == None:
        audio_Categories()    
    elif mode == 1:
#        print ""+url
        audio_Channels(url)        

def video(mode, url, title):
    if mode == None:
        video_Categories()    
    elif mode == 1:
#        print ""+url
        video_Channels(url)    

def main():
    params = get_params()
    url    = None
    title  = None
    mode   = None
    content_type = None 
     
    try:    title = urllib.unquote_plus(params['title'])
    except: pass
     
    try:    url = urllib.unquote_plus(params['url'])
    except: pass
     
    try:    mode = int(params['mode'])
    except: pass    

    try:    content_type = urllib.unquote_plus(params['content_type'])
    except: pass

    if content_type == 'audio':
        audio(mode, url, title)
    elif content_type == 'video':
        video(mode, url, title)
        
    xbmcplugin.endOfDirectory(int(sys.argv[1]))

if (__name__ == '__main__'):
    main()
